<?php
declare(strict_types=1);
/**
 * 单例服务基类
 */
namespace Service;

use Hyperf\Utils\ApplicationContext;
use Hyperf\Redis\Redis;

class BaseService
{
    const CACHE_TIME    = 600;
    const rdb_num       = 10;
    const CHUNK_SIZE    = 200;
    //每页条数
    protected $page = 1;
    //每页条数
    protected $limit = 10;
    
    /**
     * instance
     * @access private
     * @var    array
     */
    private static $instance;

    /**
     * get instance
     * @access   public
     * @return   static
     */
    public static function instance()
    {
        $class_name = get_called_class();

        if (empty(self::$instance[$class_name])) {
            self::$instance[$class_name] = new static();
        }
        return self::$instance[$class_name];

    }
    
    /**
     * 获取redis 对象
     */
    public function getRedisObj() {
        $container = ApplicationContext::getContainer();
        return $container->get(Redis::class);
    }
    
    /**
     * 访问频率控制
     *
     * @param string $key   缓存KEY
     * @param int $period   限制周期(s)
     * @param int $limit    每个周期内最大允许访问次数
     * @param boolean  $is_key 是否删除key
     * @return boolean TRUE: 访问次数未超限, FALSE:访问次数已超限
     */
    public function visitFrequency($key, $period, $limit,$is_key = false )
    {
        $redis = $this->getRedisObj();
        if ($redis->exists($key)) {
    
            if( $redis->ttl($key) <= 1 ) {
                $redis->del($key);
                return true;
            }
    
            $times = $redis->incr($key);
            if ($times > $limit) {
                return false;
            }
        } else {
            $redis->incr($key);
            $redis->expire($key,$period);
        }
        return true;
    }
}